//
// FileDowningTableViewCell.m
// LBXDownLoad
//
// Created by lbxia on 2021/4/25
//
//
    

#import "FileDowningTableViewCell.h"
#import "LBXProgressView.h"
#import "LBXDownLoadItem.h"


@implementation FileDowningTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    _progressView.backgroundColor = [UIColor colorWithRed:238/255. green:238/255. blue:238/255. alpha:1.0];
}


- (void)dealloc
{
    NSLog(@"VideoDownLoadTableViewCell dealloc");
}

+ (instancetype)instanceWithEditing:(BOOL)editing
{
    if (editing) {
        return  [[[NSBundle mainBundle]loadNibNamed:@"FileDowningTableViewCell" owner:nil options:nil]lastObject];
    }
    else
    {
        return  [[[NSBundle mainBundle]loadNibNamed:@"FileDowningTableViewCell" owner:nil options:nil]firstObject];
    }
}


- (void)setItem:(LBXDownLoadItem *)item
{
    if (_item != item) {
        _item = item;
    }
        
    dispatch_async(dispatch_get_main_queue(), ^{
        [self update];
    });
}

- (void)update
{
    if ( _item.status == LBXDownloadStatus_Completed) {
        
        //判断文件是否存在，存在则表示下载完成，不存在则下载异常
        _labelDownLoadStatus.text = @"缓存完成";
        
    }
    else if (_item.status == LBXDownloadStatus_Running)
    {
        _labelDownLoadStatus.text = @"正在缓存";
    }
    else if (_item.status == LBXDownloadStatus_Suspended)
    {
        _labelDownLoadStatus.text = @"已暂停";
    }
    else if (_item.status == LBXDownloadStatus_Failed)
    {
        _labelDownLoadStatus.text = @"缓存失败";
    }
    else if (_item.status == LBXDownloadStatus_Readying  )
    {
        _labelDownLoadStatus.text = @"等待缓存";
    }
    else
    {
        _labelDownLoadStatus.text = @"等待缓存";
    }
    
        
     _labelDescription.text = [_item.remoteURL lastPathComponent];
    
    
    if ( _item.fileSize > 0 && _item.fileSize >= _item.downSize) {
        
        CGFloat progress = ((CGFloat)_item.downSize) / _item.fileSize;
        
        NSLog(@"progress:%f",progress);
        
        _progressView.progress = progress;
        
        _labelDownLoadProgress.text = [NSString stringWithFormat:@"%@/%@",[self stringWithBytes:_item.downSize],[self stringWithBytes:_item.fileSize] ];
    }
}

- (NSString*)stringWithBytes:(int64_t)size
{
    static float unitMB = 1024*1024*1.0;
    static float unitGB = 1024*1024*1.0 *1024;
    
    if (size > unitGB) {
        return [NSString stringWithFormat:@"%.1fG",size/unitGB];
    }
    
    return [NSString stringWithFormat:@"%.1fM",size/unitMB];
}


@end
